import IPointer from "../../interfaces/IPointer";
import GlobalEvent from "../../global/GlobalEvent";

export default class Wheel extends Laya.Script {

    constructor() { super(); }

    private prePoint: IPointer;

    private isTouch: boolean = false;


    public wheel: Laya.Sprite;

    public point: Laya.Sprite;
    onEnable(): void {

        let owner = this.owner as Laya.Sprite;

        this.wheel = owner.getChildByName('wheel') as Laya.Sprite;
        this.point = owner.getChildByName('point') as Laya.Sprite;

    }

    onStageMouseDown(event: Laya.Event) {
        this.isTouch = true;

        let owner = this.owner as Laya.Sprite;
        owner.x = Laya.stage.mouseX;
        owner.y = Laya.stage.mouseY;
        this.prePoint = {
            x: owner.x,
            y: owner.y
        }

        GlobalEvent.instance.event('wheel_start');
        // this.onRecordPoint();
        // this.startPointRecord();
    }

    onStageMouseUp() {
        this.isTouch = false;
        // this.prePoint = null;
        // this.stopPointRecord();

        Laya.Tween.to(this.point, {x: 50, y: 50}, 200);

        GlobalEvent.instance.event('wheel_stop');
    }


    onStageMouseMove() {
        if (!this.isTouch) {
            return;
        }

        let newPoint: IPointer = {
            x: Laya.stage.mouseX,
            y: Laya.stage.mouseY
        }
        let angle = Math.atan2(newPoint.y - this.prePoint.y, newPoint.x - this.prePoint.x);
        GlobalEvent.instance.event('wheel_change', Math.PI * 2 - angle);
        
        let distance = this.distance(this.prePoint.x, this.prePoint.y, newPoint.x, newPoint.y);

        if (distance < 50) {
            let x = newPoint.x - this.prePoint.x + 50;
            let y = newPoint.y - this.prePoint.y + 50;
            this.point.pos(x, y)
        } else {
            let x = 50 / distance * (newPoint.x - this.prePoint.x) + 50
            let y = 50 / distance * (newPoint.y - this.prePoint.y) + 50    
            this.point.pos(x, y);

            let owner = this.owner as Laya.Sprite;
        }


    }

    startPointRecord() {
        Laya.timer.loop(100, this, this.onRecordPoint)
    }

    stopPointRecord() {
        Laya.timer.clear(this, this.onRecordPoint);
    }

    onRecordPoint() {
        this.prePoint = {
            x: Laya.stage.mouseX,
            y: Laya.stage.mouseY
        };

    }
    distance(x1, y1, x2, y2): number {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
    }
    onDisable(): void {
    }
}